﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraTab;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using BW.Mes.WinForms.BasicData;

namespace BW.Mes.WinForms.BasicData
{
    public partial class ALLBOM : DevExpress.XtraEditors.XtraForm
    {
        private BomForm.BomModel _bom;
        private DevExpress.XtraTreeList.TreeList treeList;
        private List<BomSparepartViewModel> spareparts;
        public ALLBOM(BomForm.BomModel bom)
        {
            InitializeComponent();
            _bom = bom;
            // 显示BOM信息到第一个Tab页
            if (this.Controls[0] is DevExpress.XtraTab.XtraTabControl tabControl && tabControl.TabPages.Count > 0)
            {
                // 只保留前两个Tab（BOM信息、BOM配件），移除工艺流程Tab
                while (tabControl.TabPages.Count > 2)
                {
                    tabControl.TabPages.RemoveAt(tabControl.TabPages.Count - 1);
                }
                var tabPage = tabControl.TabPages[0];
                tabPage.Controls.Clear();
                var table = new TableLayoutPanel
                {
                    ColumnCount = 2,
                    RowCount = 9,
                    AutoSize = true,
                    Location = new System.Drawing.Point(20, 20)
                };
                table.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
                table.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
                table.Controls.Add(new Label { Text = "BOM编号:", AutoSize = true, Font = new Font("微软雅黑", 11) }, 0, 0);
                table.Controls.Add(new Label { Text = _bom.BomCode, AutoSize = true, Font = new Font("微软雅黑", 11, FontStyle.Bold) }, 1, 0);
                table.Controls.Add(new Label { Text = "BOM名称:", AutoSize = true, Font = new Font("微软雅黑", 11) }, 0, 1);
                table.Controls.Add(new Label { Text = _bom.BomName, AutoSize = true, Font = new Font("微软雅黑", 11, FontStyle.Bold) }, 1, 1);
                table.Controls.Add(new Label { Text = "版本号:", AutoSize = true, Font = new Font("微软雅黑", 11) }, 0, 2);
                table.Controls.Add(new Label { Text = _bom.Version, AutoSize = true, Font = new Font("微软雅黑", 11, FontStyle.Bold) }, 1, 2);
                table.Controls.Add(new Label { Text = "类型:", AutoSize = true, Font = new Font("微软雅黑", 11) }, 0, 3);
                table.Controls.Add(new Label { Text = _bom.BomType, AutoSize = true, Font = new Font("微软雅黑", 11, FontStyle.Bold) }, 1, 3);
                table.Controls.Add(new Label { Text = "日产量:", AutoSize = true, Font = new Font("微软雅黑", 11) }, 0, 4);
                table.Controls.Add(new Label { Text = _bom.BomNumber, AutoSize = true, Font = new Font("微软雅黑", 11, FontStyle.Bold) }, 1, 4);
                table.Controls.Add(new Label { Text = "预计成本:", AutoSize = true, Font = new Font("微软雅黑", 11) }, 0, 5);
                table.Controls.Add(new Label { Text = _bom.BomMoney, AutoSize = true, Font = new Font("微软雅黑", 11, FontStyle.Bold) }, 1, 5);
                table.Controls.Add(new Label { Text = "BOM描述:", AutoSize = true, Font = new Font("微软雅黑", 11) }, 0, 6);
                table.Controls.Add(new Label { Text = _bom.BomMsg, AutoSize = true, Font = new Font("微软雅黑", 11, FontStyle.Bold) }, 1, 6);
                table.Controls.Add(new Label { Text = "创建人:", AutoSize = true, Font = new Font("微软雅黑", 11) }, 0, 7);
                table.Controls.Add(new Label { Text = _bom.CreatedBy, AutoSize = true, Font = new Font("微软雅黑", 11, FontStyle.Bold) }, 1, 7);
                table.Controls.Add(new Label { Text = "创建时间:", AutoSize = true, Font = new Font("微软雅黑", 11) }, 0, 8);
                table.Controls.Add(new Label { Text = _bom.CreatedAt.ToString(), AutoSize = true, Font = new Font("微软雅黑", 11, FontStyle.Bold) }, 1, 8);
                tabPage.Controls.Add(table);
            }
            if (xtraTabControl1.TabPages.Count > 1)
            {
                var tabPage2 = xtraTabControl1.TabPages[1];
                tabPage2.Controls.Clear();

                // 添加"创建"按钮
                var panelTop = new Panel
                {
                    Dock = DockStyle.Top,
                    Height = 40
                };
                var btnCreate = new Button
                {
                    Text = "创建",
                    Font = new Font("微软雅黑", 10, FontStyle.Bold),
                    Size = new Size(80, 32),
                    Location = new Point(10, 4)
                };
                btnCreate.Click += (s, e) =>
                {
                    var form = new BW.Mes.WinForms.BasicData.AddBomForm();
                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        // 重新加载配件数据并刷新treeList
                        spareparts = GetBomSpareparts();
                        treeList.DataSource = spareparts;
                        treeList.RefreshDataSource();
                        treeList.ExpandAll();
                    }
                };
                panelTop.Controls.Add(btnCreate);
                tabPage2.Controls.Add(panelTop);

                spareparts = GetBomSpareparts();

                // 创建树形结构
                treeList = new DevExpress.XtraTreeList.TreeList();
                treeList.Dock = DockStyle.Fill;
                treeList.DataSource = spareparts;
                treeList.KeyFieldName = "Id";
                treeList.ParentFieldName = "ParentId";
                
                // 配置树形结构的基本属性
                treeList.OptionsView.ShowIndicator = false;
                treeList.OptionsView.ShowHorzLines = true;
                treeList.OptionsView.ShowVertLines = true;
                treeList.OptionsBehavior.Editable = false;
                treeList.OptionsBehavior.ReadOnly = true;
                
                // 自动生成列
                treeList.PopulateColumns();
                
                // 展开所有节点
                treeList.ExpandAll();

                // 调试：显示Id和ParentId列
                var colId = treeList.Columns["Id"];
                if (colId != null) { colId.Visible = true; colId.VisibleIndex = 0; colId.Caption = "ID"; }
                var colParentId = treeList.Columns["ParentId"];
                if (colParentId != null) { colParentId.Visible = true; colParentId.VisibleIndex = 1; colParentId.Caption = "ParentId"; }

                // 配置列显示
                ConfigureTreeListColumns(treeList);

                tabPage2.Controls.Add(treeList);
            }
        }
        
        private void ConfigureTreeListColumns(DevExpress.XtraTreeList.TreeList treeList)
        {
            // 隐藏所有列，然后按需显示
            foreach (DevExpress.XtraTreeList.Columns.TreeListColumn col in treeList.Columns)
            {
                col.Visible = false;
            }

            // 设置要显示的列及其标题
            var columnConfigs = new Dictionary<string, string>
            {
                { "ProductCode", "物品编号" },
                { "ProductName", "物品名称" },
                { "Specification", "规格型号" },
                { "Unit", "单位" },
                { "Spend", "品牌" },
                { "NNumber", "配件数量" },
                { "BomBfb", "损耗率" }
            };

            int visibleIndex = 0;
            foreach (var config in columnConfigs)
            {
                var col = treeList.Columns[config.Key];
                if (col != null)
                {
                    col.Visible = true;
                    col.VisibleIndex = visibleIndex++;
                    col.Caption = config.Value;
                    
                    // 设置列宽
                    if (config.Key == "ProductName")
                        col.Width = 200;
                    else if (config.Key == "Specification")
                        col.Width = 150;
                    else
                        col.Width = 100;
                }
            }

            // 隐藏系统字段
            HideColumn(treeList, "Id");
            HideColumn(treeList, "ParentId");
        }

        public ALLBOM() : this(null) { }
        
        private List<BomSparepartViewModel> GetBomSpareparts()
        {
            using (var client = new HttpClient())
            {
                try
                {
                    var response = client.GetAsync("http://120.26.197.100:8022/T2/Bom/GetBomSparepart").Result;
                    if (response.IsSuccessStatusCode)
                    {
                        var json = response.Content.ReadAsStringAsync().Result;
                        var obj = JObject.Parse(json);
                        var listToken = obj["pageDatas"];
                        return listToken != null
                            ? JsonConvert.DeserializeObject<List<BomSparepartViewModel>>(listToken.ToString())
                            : new List<BomSparepartViewModel>();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"获取BOM配件数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return new List<BomSparepartViewModel>();
        }
        
        public class BomSparepartViewModel
        {
            [JsonProperty("id")]
            public long Id { get; set; }
            [JsonProperty("parentId")]
            public long ParentId { get; set; }
            [JsonProperty("productCode")]
            public string ProductCode { get; set; }
            [JsonProperty("productName")]
            public string ProductName { get; set; }
            [JsonProperty("specification")]
            public string Specification { get; set; }
            [JsonProperty("unit")]
            public string Unit { get; set; }
            [JsonProperty("spend")]
            public string Spend { get; set; }
            [JsonProperty("nNumber")]
            public int NNumber { get; set; }
            [JsonProperty("bomBfb")]
            public string BomBfb { get; set; }
        }
        
        // 隐藏列（安全设置）
        void HideColumn(DevExpress.XtraTreeList.TreeList tl, string field)
        {
            var col = tl.Columns[field];
            if (col != null) col.Visible = false;
        }

        private void tabPage2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void tabPage1_Paint(object sender, PaintEventArgs e)
        {

        }
    }
}